﻿Imports System.Timers
Imports HslCommunication
Imports HslCommunication.LogNet
Imports HslCommunication.Profinet.Siemens
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
'三菱 2000
'西门子s7 102
Public Class FormMain
    Dim objClsSysParam As New clsSysParam

    '西门子1200对象
    Dim StripperPLC As SiemensS7Net
    Dim agv_website As String
    '脱模机ip
    Dim ip_stripper As String = "172.16.20.181"
    Dim port_stripper As Integer = 102

    'PLC是否连接成功
    Dim StripperPlcConFLG As Boolean = False

    'AGV是否到位
    Dim AGVArrivedFLG As Boolean = False

    'AGV是否移动到位
    Dim AGVMoveToArrivedFLG As Boolean = False

    'Dim WithEvents timer_agv As System.Timers.Timer
    Dim thAgv As New Threading.Thread(AddressOf timer_agv_Elapsed)
    Dim timer_interval As Integer = 2000 '时间间隔

    Dim ping = New Net.NetworkInformation.Ping()

    Dim dtTaskStep As New DataTable

    Dim objClsTaskStep As New clsTaskStep

    Dim objClsProdInfo As New clsProdInfo

    Dim objClsProdSpec As New clsProdSpec

    Dim objClsTmj As New clsTmj

    Private Heart As Boolean = True
    Private agvFLG As Boolean = False
    Dim httphelper As New HttpHelper
    Private logfile As ILogNet            'log文件
    Public Sub New()
        ''加载DLL到exe的事件
        AddHandler AppDomain.CurrentDomain.AssemblyResolve, New ResolveEventHandler(AddressOf CurrentDomain_AssemblyResolve)
        ' 此调用是设计器所必需的。
        InitializeComponent()

        ' 在 InitializeComponent() 调用之后添加任何初始化。

    End Sub

    Private Function CurrentDomain_AssemblyResolve(sender As Object, args As ResolveEventArgs) As System.Reflection.Assembly
        Dim dllName As String = If(args.Name.Contains(","), args.Name.Substring(0, args.Name.IndexOf(","c)), args.Name.Replace(".dll", ""))
        dllName = dllName.Replace(".", "_")
        If dllName.EndsWith("_resources") Then
            Return Nothing
        End If
        Dim rm As New System.Resources.ResourceManager([GetType].Namespace & ".Resources", System.Reflection.Assembly.GetExecutingAssembly())
        Dim bytes As Byte() = DirectCast(rm.GetObject(dllName), Byte())
        Return System.Reflection.Assembly.Load(bytes)
    End Function
    Private Sub FormMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Control.CheckForIllegalCrossThreadCalls = False
        logfile = New LogNetDateTime(Application.StartupPath & "\\Logs", GenerateMode.ByEveryDay)
        If Not HslCommunication.Authorization.SetAuthorizationCode("e3e27344-1a9f-4d8b-b4fc-da5cae4b99bf") Then

        End If
        If Not HslControls.Authorization.SetAuthorizationCode("ce5ade06-6f14-4b0d-b9c2-0d625664dc3f") Then

        End If
        UCtmjInfo1.logfile = logfile
        'AGV到位→入货→入货到位（调取agv）→取芯座→取芯座完成（调取agv）
        connectDB()
        getTaskStep()
        getTmjIp()
        getAgvWebSite()
        getPlcStripper()
    End Sub

    ''' <summary>
    ''' 连接数据库
    ''' </summary>
    Private Sub connectDB()
        Try
            g_szInitFileName = My.Application.Info.DirectoryPath & "\Server_TMJ.ini"

            g_Server.szDrive = GetIniFile("SERVER", "DRIVE", "PostgreSQL ANSI", g_szInitFileName)
            g_Server.szIPadr = GetIniFile("SERVER", "IP", "", g_szInitFileName)
            g_Server.szDbn = GetIniFile("SERVER", "DBN", "ZHENANSF", g_szInitFileName)
            g_Server.szUid = GetIniFile("SERVER", "UID", "sa", g_szInitFileName)
            g_Server.szPas = GetIniFile("SERVER", "PAS", "sa", g_szInitFileName)
            g_Server.iOver = CInt(GetIniFile("SERVER", "OVER", "-1", g_szInitFileName))

            If False = g_fDBconnect And 0 = g_iDBconnResult Then
                If "" = g_Server.szIPadr Or "0.0.0.0" = g_Server.szIPadr Then
                Else
                    g_fDBconnect = True

                    'データベース接続
                    With g_Server
                        g_iDBconnResult = DBacs.Connect(.szDrive, .szIPadr, .szDbn, .szUid, .szPas, .iOver)
                        If 1 <> g_iDBconnResult Then
                            .szDrive = CStr(IIf("PostgreSQL" = .szDrive, "PostgreSQL ANSI", "PostgreSQL"))
                            g_iDBconnResult = DBacs.Connect(.szDrive, .szIPadr, .szDbn, .szUid, .szPas, .iOver)
                        End If
                    End With
                End If
            End If
        Catch ex As Exception
            logfile.WriteError("连接DB失败")
        End Try


    End Sub

    Private Sub getPlcStripper()
        Try
            StripperPLC = New SiemensS7Net(SiemensPLCS.S1200)
            StripperPLC.IpAddress = ip_stripper
            StripperPLC.Port = port_stripper
            StripperPLC.SetPersistentConnection()
            'StripperPLC.Rack = 0
            'StripperPLC.Slot = 0
            'StripperPLC.ConnectionType = 1
            'StripperPLC.LocalTSAP = 258
            With UCtmjInfo1
                .StripperPLC_UC = StripperPLC
                .agv_website = agv_website
                '.tmPLC.Start()

                .plcflg = True
                .thTime.Start()
                '.Timer1.Start()
            End With
            'StripperPlcConFLG = UCtmjInfo1.StripperPlcConFLG_UC
            'Try
            'Dim pingResult As Net.NetworkInformation.PingReply = ping.Send(ip_stripper)
            'If pingResult.Status = Net.NetworkInformation.IPStatus.Success Then
            'Dim connect As OperateResult = StripperPLC.ConnectServer()
            '    If connect.IsSuccess = True Then
            '        StripperPlcConFLG = connect.IsSuccess
            '        Me.Refresh()
            '    End If
            'Else

            'End If
            'Catch ex As Exception
            'End Try
        Catch ex As Exception
            logfile.WriteError("formMain.getPlcStripper:" & ex.Message)
        End Try

    End Sub

    Private Sub getTmjIp()
        Try
            Dim dttmjip As DataTable = objClsSysParam.selectTmjIp()
            If dttmjip.Rows.Count = 1 Then
                ip_stripper = dttmjip.Rows(0)("param_value").ToString()
            Else
                MsgBox("请设置脱模机IP")
            End If
        Catch ex As Exception
            logfile.WriteError("formMain.getTmjIp:" & ex.Message)
        End Try

    End Sub

    Private Sub getAgvWebSite()
        Try
            Dim dt As DataTable = objClsSysParam.selectAgvWebSite()
            If dt.Rows.Count = 1 Then
                agv_website = dt.Rows(0)("param_value").ToString()
            End If
        Catch ex As Exception
            logfile.WriteError("formMain.getAgvWebSite:" & ex.Message)
        End Try

    End Sub

    Private Sub getTaskStep()
        Try
            'timer_agv = New System.Timers.Timer
            'timer_agv.Interval = timer_interval
            'timer_agv.Start()
            agvFLG = True
            thAgv.Start()
        Catch ex As Exception
            logfile.WriteError("formMain.getTaskStep:" & ex.Message)
        End Try

    End Sub
    Public _count As Integer = 1
    Private Sub timer_agv_Elapsed() 'sender As Object, e As ElapsedEventArgs) 'Handles timer_agv.Elapsed
        Try
            While agvFLG
                'logfile.WriteInfo(_count)
                _count = _count + 1
                dtTaskStep = objClsTaskStep.SelectTaskTM()
                Dim rtn11 As String = readStripperPlc("DB47.DBX0.0")
                If rtn11 = False.ToString() Then '脱模机闲
                    For index = 0 To dtTaskStep.Rows.Count - 1
                        If dtTaskStep.Rows(index)("status").Equals("开始卸载") Then
                            UCtmjInfo1.tmj_task_step_id = String.Empty
                            UCtmjInfo1.agv_id = String.Empty
                            Dim pn As Integer = GetProdNo(dtTaskStep.Rows(index)("prod_id").ToString())
                            Dim b1 As Boolean = writeStripperBytePlc("DB47.DBX10", Byte.Parse(pn)) 'AGV车上支座型号写入
                            If b1 = False Then
                                writeStripperBytePlc("DB47.DBX10", Byte.Parse(pn)) 'AGV车上支座型号写入
                            End If
                            objClsTmj.update_tmj_prod_no_write(pn, dtTaskStep.Rows(index)("sys_id").ToString())
                            Threading.Thread.Sleep(2000)
                            Dim b2 As Boolean = writeStripperBoolPlc("DB47.DBX11.0", True) 'AGV车到位写入
                            If b2 = False Then
                                writeStripperBoolPlc("DB47.DBX11.0", True) 'AGV车到位写入
                            End If
                            objClsTmj.update_tmj_arrive_write(b2, dtTaskStep.Rows(index)("sys_id").ToString())
                            '执行数据库更新
                            UCtmjInfo1.tmj_task_step_id = dtTaskStep.Rows(index)("task_id").ToString()
                            UCtmjInfo1.agv_id = dtTaskStep.Rows(index)("agv").ToString()
                        End If
                        'If dtTaskStep.Rows(index)("status").Equals("任务完成") Then
                        '    Dim b3 As Boolean = writeStripperBoolPlc("DB47.DBX11.3", True) 'AGV移动到位写入
                        'End If
                    Next
                Else
                    For index = 0 To dtTaskStep.Rows.Count - 1
                        If String.IsNullOrEmpty(UCtmjInfo1.tmj_task_step_id) = False Then
                            If dtTaskStep.Rows(index)("status").Equals("任务完成") And
                            dtTaskStep.Rows(index)("task_id").ToString().Equals(UCtmjInfo1.tmj_task_step_id) Then
                                Dim b3 As Boolean = writeStripperBoolPlc("DB47.DBX11.3", True) 'AGV移动到位写入
                                If b3 = False Then
                                    writeStripperBoolPlc("DB47.DBX11.3", True) 'AGV移动到位写入
                                End If
                            End If
                        End If
                    Next
                    'Dim dtTmj As DataTable = objClsTaskStep.SelectTmj(UCtmjInfo1.tmj_task_step_id)
                    'If dtTmj.Rows.Count = 1 Then
                    '    If dtTaskStepRecord.Rows(0)("status").Equals("任务完成") Then
                    '        UCtmjInfo1.lblStatusRtn.Text = b3.ToString()
                    '    End If
                    '    Dim dtTaskStepRecord As DataTable = objClsTaskStep.SelectTaskStepRecord(UCtmjInfo1.tmj_task_step_id)
                    '    If dtTaskStepRecord.Rows.Count = 1 Then
                    '    End If
                    'End If
                End If

                Me.Invoke(datagridRefreshCaller, dtTaskStep)
            End While
        Catch ex As Exception
            logfile.WriteError("formMain.timer_agv_Elapsed:" & ex.Message)
            'timer_agv.Stop()
            MsgBox("与服务器断开连接，请检查网络状态。")
        End Try

    End Sub
    Delegate Sub datagridRefreshDelegate(_dt As DataTable)
    Dim datagridRefreshCaller As New datagridRefreshDelegate(AddressOf datagridRefresh)
    Private Sub datagridRefresh(_dt As DataTable)
        Try
            dgvTaskStep.AutoGenerateColumns = False
            Me.dgvTaskStep.DataSource = dtTaskStep
        Catch ex As Exception
            logfile.WriteError("formMain.datagridRefresh:" & ex.Message)
        End Try

    End Sub
    Private Function GetProdNo(prod_id As String) As Integer
        Try


            Dim rtn As Integer = 0
            Dim dtt As DataTable = objClsProdInfo.SelectProdInfo(prod_id)
            'Dim dtPI As DataTable = objClsProdSpec.SelectProdSpec("%" & dtt.Rows(0)("prod_spec_id") & "%")
            Dim dtPI As DataTable = objClsProdSpec.SelectProdSpec(dtt.Rows(0)("prod_spec_id"))
            If dtPI.Rows.Count > 0 Then
                If dtPI.Rows(0)("prod_spec").ToString().Contains("500") Then
                    'And dtPI.Rows(0)("prod_spec").ToString().ToUpper().Contains("LNR")
                    rtn = 1
                End If
                'If dtPI.Rows(0)("prod_spec").ToString().Contains("500") Then
                'And dtPI.Rows(0)("prod_spec").ToString().ToUpper().Contains("LRB") Then
                'rtn = 2
                'End If
                If dtPI.Rows(0)("prod_spec").ToString().Contains("600") Then
                    'And dtPI.Rows(0)("prod_spec").ToString().ToUpper().Contains("LNR") Then
                    rtn = 3
                End If
                If dtPI.Rows(0)("prod_spec").ToString().Contains("600") Then
                    'And dtPI.Rows(0)("prod_spec").ToString().ToUpper().Contains("LRB") Then
                    rtn = 4
                End If
                If dtPI.Rows(0)("prod_spec").ToString().Contains("700") Then
                    'And dtPI.Rows(0)("prod_spec").ToString().ToUpper().Contains("LNR") Then
                    rtn = 5
                End If
                If dtPI.Rows(0)("prod_spec").ToString().Contains("700") Then
                    'And dtPI.Rows(0)("prod_spec").ToString().ToUpper().Contains("LRB") Then
                    rtn = 6
                End If
                'If dtPI.Rows(0)("prod_spec").ToString().Contains("800") Then
                '    'And dtPI.Rows(0)("prod_spec").ToString().ToUpper().Contains("LNR") Then
                '    rtn = 7
                'End If
                If dtPI.Rows(0)("prod_spec").ToString().Contains("800") Then
                    'And dtPI.Rows(0)("prod_spec").ToString().ToUpper().Contains("LRB") Then
                    rtn = 8
                End If
                'If dtPI.Rows(0)("prod_spec").ToString().Contains("900") Then
                '    'And dtPI.Rows(0)("prod_spec").ToString().ToUpper().Contains("LNR") Then
                '    rtn = 9
                'End If
                If dtPI.Rows(0)("prod_spec").ToString().Contains("900") Then
                    'And dtPI.Rows(0)("prod_spec").ToString().ToUpper().Contains("LRB") Then
                    rtn = 10
                End If
                'If dtPI.Rows(0)("prod_spec").ToString().Contains("1000") Then
                '    'And dtPI.Rows(0)("prod_spec").ToString().ToUpper().Contains("LNR") Then
                '    rtn = 11
                'End If
                If dtPI.Rows(0)("prod_spec").ToString().Contains("1000") Then
                    'And dtPI.Rows(0)("prod_spec").ToString().ToUpper().Contains("LRB") Then
                    rtn = 12
                End If
            End If

            Return rtn
        Catch ex As Exception

            logfile.WriteError("formMain.GetProdNo:" & ex.Message)
            Return 0
        End Try
    End Function

    ''' <summary>
    ''' 执行
    ''' </summary>
    Private Sub Worker()
        '从数据库中获取通讯检测为true
        '异常状态
        '脱模机忙闲状态
        'AGV到位状态(支座写入状态)
        '脱模机拿取支座完成状态
        'AGV移动到位状态
        '脱模机脱模完成状态
        'AGV离开状态

        '从数据库中取出上面的标注状态
        If True And False And True And AGVArrivedFLG And False Then
            'True,脱模机为闲时，无异常报警，AGV到位True，脱模机拿取支座完成状态False
            writeStripperBoolPlc("DB47.DBX11.0", "1") 'AGV车到位写入
            writeStripperBytePlc("DB47.DBX10", "1") 'AGV车上支座型号写入
            '此时脱模机忙闲状态应该改为忙了
        ElseIf True And False And False And AGVArrivedFLG And True And False Then
            'True,脱模机为忙时，无异常报警，AGV到位True，脱模机拿取支座完成状态True，AGV移动到位False
            'AGVMoveTo() 'agv移动到脱模机下的位置
        ElseIf True And False And False And AGVArrivedFLG And True And True Then
            'True,脱模机为忙时，无异常报警，AGV到位True(最好这里为true，方便统一动作完成)，脱模机拿取支座完成状态True，AGV移动到位True
            writeStripperBoolPlc("DB47.DBX11.3", "1") 'AGV移动到位写入
            'writeStripperPlc("DB47.DBX11.1", "1") 'AGV小车成功取到脱下芯座
        ElseIf True And False And False And AGVArrivedFLG And True And True And True Then
            'True,脱模机为忙时，无异常报警，AGV到位True(最好这里为true，方便统一动作完成)，脱模机拿取支座完成状态True，AGV移动到位True，脱模机脱模完成True
            'AGVLeave()
        ElseIf True And False And False And AGVArrivedFLG And True And True And True And True Then
            'True,脱模机为忙时，无异常报警，AGV到位True(最好这里为true，方便统一动作完成)，脱模机拿取支座完成状态True，AGV移动到位True，脱模机脱模完成True,AGV离开True
            writeStripperBoolPlc("DB47.DBX11.3", "0") 'AGV离开写入
            '此时脱模机忙闲状态应该改为闲了
        ElseIf True And True Then
            '发出异常警报
        End If

    End Sub

    Private Function readStripperPlc(place As String) As String
        '执行plc读取操作
        'If StripperPlcConFLG_UC Then
        Try
            Return readStripper(place, StripperPLC)
        Catch ex As Exception
            Return "false"
            logfile.WriteError("formMain.readStripperPlc:" & ex.Message)
        End Try

        'Else
        '    Return String.Empty
        'End If
    End Function

    Private Function readStripper(place As String, plc As SiemensS7Net) As String
        Try
            '	RGV当前状态	Int	2.0
            Dim status As String = plc.ReadBool(place).Content
            Return status
        Catch ex As Exception

            logfile.WriteError("formMain.readStripper:" & ex.Message)
            Return "false"
        End Try

    End Function
    Private Function readStripperByte(place As String, plc As SiemensS7Net) As String
        Try
            Dim status As String = plc.ReadByte(place).Content '	RGV当前状态	Int	2.0
            Return status
        Catch ex As Exception

            logfile.WriteError("formMain.readStripperByte:" & ex.Message)
            Return ""
        End Try


    End Function

    Private Function writeStripperBoolPlc(place As String, val As Boolean) As Boolean
        Try
            If UCtmjInfo1.StripperPlcConFLG_UC Then
                Return WriteStripperBool(place, val, StripperPLC)
            Else
                Return False
            End If
        Catch ex As Exception

            logfile.WriteError("formMain.writeStripperBoolPlc:" & ex.Message)
            Return False
        End Try

    End Function
    Private Function WriteStripperBool(place As String, val As Boolean, plc As SiemensS7Net) As Boolean
        '查询脱模机状态等条件
        'Dim dt As DataTable = objStripper.getList(strippername)
        'If dt.Rows(0)("status").ToString().Equals("1") Then
        '    '如果满足条件 则进行更新
        'End If
        Try

            If UCtmjInfo1.StripperPlcConFLG_UC Then
                Dim OperR As OperateResult = plc.Write(place, val)
                Return OperR.IsSuccess
            Else
                Return False
            End If
        Catch ex As Exception

            logfile.WriteError("formMain.WriteStripperBool:" & ex.Message)
            Return False
        End Try
    End Function

    Private Function writeStripperBytePlc(place As String, val As Byte) As Boolean
        Try
            If UCtmjInfo1.StripperPlcConFLG_UC Then
                Return writeStripperByte(place, val, StripperPLC)
            Else
                Return False
            End If
        Catch ex As Exception

            logfile.WriteError("formMain.writeStripperBytePlc:" & ex.Message)
            Return False
        End Try

    End Function

    Private Function writeStripperByte(place As String, val As Byte, plc As SiemensS7Net) As Boolean
        Try
            '查询脱模机状态等条件
            'Dim dt As DataTable = objStripper.getList(strippername)
            'If dt.Rows(0)("status").ToString().Equals("1") Then
            '    '如果满足条件 则进行更新
            'End If

            If UCtmjInfo1.StripperPlcConFLG_UC Then
                Dim OperR As OperateResult = plc.Write(place, val)
                Return OperR.IsSuccess

            Else
                Return False
            End If
        Catch ex As Exception
            logfile.WriteError("formMain.writeStripperByte:" & ex.Message)
            Return False
        End Try


    End Function

    Private Sub FormMain_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
        Try
            Me.Hide()
            e.Cancel = True
        Catch ex As Exception
            logfile.WriteError("formMain.FormMain_FormClosing:" & ex.Message)
        End Try

    End Sub

    Private Sub FormMain_Closed(sender As Object, e As EventArgs) Handles Me.Closed
        Try
            DBacs.Disconnect()
        Catch ex As Exception
            logfile.WriteError("formMain.FormMain_Closed:" & ex.Message)
        End Try

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Try
            If MsgBox("确认要进行关闭吗？关闭后将无法自动进行自动脱模", vbYesNo, "提示") = vbYes Then
                RemoveHandler Me.FormClosing, AddressOf FormMain_FormClosing
                NotifyIcon1.Dispose()

                If UCtmjInfo1.StripperPlcConFLG_UC Then
                    StripperPLC.ConnectClose()
                    agvFLG = False
                    UCtmjInfo1.plcflg = False

                    Try
                        If thAgv.IsAlive Then
                            thAgv.Abort()
                        End If
                    Catch ex As Exception

                    End Try
                    System.Threading.Thread.Sleep(3000)
                    Try
                        If UCtmjInfo1.thTime.IsAlive Then
                            UCtmjInfo1.thTime.Abort()
                        End If
                    Catch ex As Exception

                    End Try
                    System.Threading.Thread.Sleep(3000)
                    'timer_agv.Stop()
                    'timer_agv.Enabled = False
                    'UCtmjInfo1.tmPLC.Stop()
                End If
                logfile.WriteError("formMain.Button1_Click:关闭画面")
                Close()
            Else
                AddHandler Me.FormClosing, AddressOf FormMain_FormClosing
            End If
        Catch ex As Exception
            logfile.WriteError("formMain.Button1_Click:" & ex.Message)
        End Try


    End Sub

    Private Sub NotifyIcon1_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles NotifyIcon1.MouseDoubleClick
        Try
            Me.Show()
        Catch ex As Exception
            logfile.WriteError("formMain.NotifyIcon1_MouseDoubleClick:" & ex.Message)
        End Try


    End Sub
End Class
